import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

// 定义一个pinia store
// 这里使用了defineStore函数来定义store，并传入一个唯一的id作为标识符。
// 第一种写法，组合式api
const useCounterStore = defineStore(
  'counter',
  () => {
    const count = ref(10)
    const name = ref('李四')
    const age = ref(20)
    const doubleCount = computed(() => count.value * 2)
    const getAddAge = computed(() => age.value + 100)
    const getNameAndAge = computed(() => name.value + getAddAge.value)
    function increment() {
      count.value++
      name.value = count.value % 2 == 0 ? '李四' : '张三'
    }
    function decrement() {
      count.value--
      name.value = count.value % 2 == 0 ? '李四' : '张三'
    }
    return { count, name, age, doubleCount, getAddAge, getNameAndAge, increment, decrement }
  },
  {
    persist: {
      enabled: true, //Store中数据持久化生效
      strategies: [
        {
          // key: 'counterStore', // 修改存在缓存中的key值,默认值counter
          storage: localStorage, // 修改存储方式为localStorage
          paths: ['count'] // 只持久化count，此时刷新页面count数据会被保留，其他state将会重置
        }
      ]
    }
  }
)

// 第二种写法，对象写法
/* const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 10,
    name: '李四',
    age: 20
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    getAddAge: (state) => {
      return state.age + 100
    },
    getNameAndAge() {
      return this.name + this.getAddAge // 调用其它getter
    }
  },
  actions: {
    increment() {
      this.count++
      this.name = this.count % 2 == 0 ? '李四' : '张三'
    },
    decrement() {
      this.count--
      this.name = this.count % 2 == 0 ? '李四' : '张三'
    }
  },
  // 开启数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        // key: 'counterStore', // 修改存在缓存中的key值,默认值counter
        storage: localStorage, // 修改存储方式为localStorage
        paths: ['count'] // 只持久化count，此时刷新页面count数据会被保留，其他state将会重置
      }
    ]
  }
}) */
export default useCounterStore
